package com.xh.baselibrary.utils;

import android.content.Context;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Author: GW00239435
 */
public class AssetsUtils {
    public static void doWriteFileToDevice(Context context, String assetsPath, String destParentPath) {
        try {
            String[] files = context.getAssets().list(assetsPath);
            if (files != null && files.length > 0) {
                //文件夹
                String parentPath = destParentPath + File.separator + assetsPath;
                File destParentFile = new File(parentPath);
                if (!destParentFile.exists()) destParentFile.mkdirs();
                for (String file : files) {
                    doWriteFileToDevice(context, assetsPath + File.separator + file, destParentPath);
                }
            } else {
                //文件
                File destParentFile = new File(destParentPath + File.separator + assetsPath);
                File parentFile = destParentFile.getParentFile();
                while (parentFile != null && !parentFile.exists()) {
                    parentFile.mkdirs();
                    parentFile = parentFile.getParentFile();
                }
//                if(destParentFile.exists()){
//                    return;
//                }
                InputStream inputStream = context.getAssets().open(assetsPath);
                byte[] buff = new byte[2048];
                FileOutputStream outputStream = new FileOutputStream(destParentFile);
                int len = 0;
                while ((len = inputStream.read(buff)) != -1) {
                    outputStream.write(buff, 0, len);
                }
                outputStream.flush();
                CloseableUtils.close(outputStream);
                CloseableUtils.close(inputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
